package com.cskaoyan.convert;

import lombok.SneakyThrows;
import org.springframework.core.convert.converter.Converter;

import java.text.SimpleDateFormat;
import java.util.Date;

public class String2DateConverter implements Converter<String, Date> {

    @SneakyThrows
    @Override
    public Date convert(String s) {
        Date date = null;
        String pattern1 = "yyyy-MM-dd";
        String pattern2 = "yyyy-MM-dd HH:mm:ss";

        // 这里不需要判断s为空，如果请求参数为空，那么不会进入到该转换器中，也就不会出现NullPointerException
        // if (s == null)
        //     System.out.println("null");

        if (pattern1.length() == s.length()) {
            date = new SimpleDateFormat(pattern1).parse(s);
        } else if (pattern2.length() == s.length()) {
            date = new SimpleDateFormat(pattern2).parse(s);
        }

        return date;
    }

}
